import { MenuDataItem } from "@ant-design/pro-layout";
import { CrownOutlined } from "@ant-design/icons";
import ACCESS_ENUM from "@/access/accessEnum";

// 菜单列表
export const menus = [
  {
    path: "/",
    name: "主页",
  },
  {
    path: "/banks",
    name: "题库",
  },
  {
    path: "/questions",
    name: "题目",
  },
  {
    path: "/mockInterview/add",
    name: "模拟面试",
  },
  {
    name: "源码",
    path: "https://gitee.com/bhcb/awei-do-exercises",
    target: "_blank",
  },
  {
    path: "/admin",
    name: "管理",
    icon: <CrownOutlined />,
    access: ACCESS_ENUM.ADMIN,
    children: [
      {
        path: "/admin/user",
        name: "用户管理",
        access: ACCESS_ENUM.ADMIN,
      },
      {
        path: "/admin/bank",
        name: "题库管理",
        access: ACCESS_ENUM.ADMIN,
      },
      {
        path: "/admin/question",
        name: "题目管理",
        access: ACCESS_ENUM.ADMIN,
      },
    ],
  },
] as MenuDataItem[];

// 额外的路由权限配置（不在菜单中显示的路由）
export const extraRoutes = [
  {
    path: "/bank/:questionBankId",
    access: ACCESS_ENUM.USER,
  },
  {
    path: "/bank/:questionBankId/question/:questionId",
    access: ACCESS_ENUM.USER,
  },
  {
    path: "/question/:questionId",
    access: ACCESS_ENUM.USER,
  },
] as MenuDataItem[];

// 根据全部路径查找菜单
export const findAllMenuItemByPath = (path: string): MenuDataItem | null => {
  // 先在菜单中查找
  const menuItem = findMenuItemByPath(menus, path);
  if (menuItem) {
    return menuItem;
  }
  // 再在额外路由中查找
  return findMenuItemByPath(extraRoutes, path);
};

// 根据路径查找菜单（递归）
export const findMenuItemByPath = (
  menuItems: MenuDataItem[],
  path: string,
): MenuDataItem | null => {
  for (const menu of menuItems) {
    // 支持动态路由匹配
    if (menu.path && matchDynamicPath(path, menu.path)) {
      return menu;
    }
    if (menu.children) {
      const matchedMenuItem = findMenuItemByPath(menu.children, path);
      if (matchedMenuItem) {
        return matchedMenuItem;
      }
    }
  }
  return null;
};

// 匹配动态路由
const matchDynamicPath = (actualPath: string, routePath: string): boolean => {
  const actualParts = actualPath.split('/');
  const routeParts = routePath.split('/');

  if (actualParts.length !== routeParts.length) {
    return false;
  }

  return routeParts.every((part, index) => {
    // 如果是动态参数（以:开头），则匹配任意值
    if (part.startsWith(':')) {
      return true;
    }
    return part === actualParts[index];
  });
};
